﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Abp.AutoMapper;
using System.Data.Entity;
using Abp.Domain.Repositories;
using MyCompanyName.AbpZeroTemplate.Prm.Project.Dto;
using MyCompanyName.AbpZeroTemplate.Prm.Project;
using Abp.Application.Services.Dto;
using MyCompanyName.AbpZeroTemplate.Prm.Admin;
using Abp.Domain.Uow;
using MyCompanyName.AbpZeroTemplate.Authorization.Users;
using MyCompanyName.AbpZeroTemplate.Prm.Project.ProjectTaskExport;
using System.Web;
using System.IO;
using MyCompanyName.AbpZeroTemplate.Prm.Authorization;


namespace MyCompanyName.AbpZeroTemplate.Prm.Project
{
    public class InquiryAppService : AbpZeroTemplateAppServiceBase, IInquiryAppService
    {

        private readonly IRepository<Inquiry.Inquiry, int> inquiryRepository;
        private readonly IRepository<Inquiry.InquiryReply, int> inquiryReplyRepository;
        private readonly PermissionService permissionService;
        private readonly IRepository<Product, int> productRepository;
        private readonly ProjectManager projectManager;
        private readonly IRepository<UserQuan, int> UserQuanRepository;
        private readonly SubstanceManager substanceManager;
        private readonly UserManager userManager;

        private readonly MailManager mailManagerRepository;
        public InquiryAppService(IRepository<Inquiry.Inquiry, int> _inquiryRepository,
            IRepository<UserQuan, int> _UserQuanRepository,
            SubstanceManager _substanceManager,
             UserManager _userManager,
            MailManager _mailManagerRepository,
            ProjectManager _projectManager,
            IRepository<Product, int> _productRepository,
            IRepository<Inquiry.InquiryReply, int> _inquiryReplyRepository,
             PermissionService _permissionService
            )
        {
            inquiryReplyRepository = _inquiryReplyRepository;
            inquiryRepository = _inquiryRepository;
            userManager = _userManager;
            substanceManager = _substanceManager;
            mailManagerRepository = _mailManagerRepository;
            UserQuanRepository = _UserQuanRepository;
            projectManager = _projectManager;
            productRepository = _productRepository;
            permissionService = _permissionService;
        }


        public List<dynamic> GetInquiryStatus()
        {
            List<dynamic> dy = new List<dynamic>();

            foreach (Inquiry.InquiryStatus c in (Inquiry.InquiryStatus[])Enum.GetValues(typeof(Inquiry.InquiryStatus)))
            {
                dy.Add(new { key = c.ToString(), value = (int)c });
            }
            return dy;
        }

        public List<dynamic> GetQuiryNo(string name)
        {
            List<dynamic> lst = new List<dynamic>();

            var productNos1 = inquiryRepository.GetAll().Where(x => x.InquiryNo.Contains(name)).Select(x => x.InquiryNo).Distinct().ToList();
            var productNos2 = projectManager.projectRepository.GetAll().Where(x => x.ProductNo.Contains(name)).Select(x => x.ProductNo).Distinct().ToList();


            foreach (var item in productNos2)
            {
                var p = productRepository.GetAll().Where(x => x.Code == item).FirstOrDefault();
                if (p != null)
                {
                    lst.Add(
                       new
                       {
                           Id = System.Guid.NewGuid(),
                           name = item,
                           subId = p.SubstanceId
                       });
                }
                else
                {
                    lst.Add(
                          new
                          {
                              Id = System.Guid.NewGuid(),
                              name = item,
                              subId = 0
                          });
                }

            }

            foreach (var item in productNos1)
            {
                var p = inquiryRepository.GetAll().Where(x => x.InquiryNo == item).FirstOrDefault();
                int subId = 0;

                if (p != null && p.SubId > 0)
                {
                    subId = p.SubId;
                }


                if (productNos2.Contains(item) && subId > 0)
                {
                    var _item = lst.Where(x => x.name == item).FirstOrDefault();
                    _item.subId = subId;
                }
                else
                {
                    lst.Add(
                             new
                             {
                                 Id = System.Guid.NewGuid(),
                                 name = item,
                                 subId = subId
                             });
                }
            }


            return lst;
        }

        public string GetInquiryProjectNo()
        {
            string year = DateTime.Now.Year.ToString();
            int index = 1;
            string projectNo = "";
            do
            {
                projectNo = string.Format("{0}{1}", year, index.ToString("0000"));

                if (!inquiryRepository.GetAll().Any(x => x.ProjectNo == projectNo))
                {
                    break;
                }
                index++;
            }
            while (true);

            return projectNo;
        }

        public PagedResultOutput<GetInquiryOutPut> GetInquirys(string productNo)
        {
            var userId = AbpSession.UserId;
            var subIds = productRepository.GetAll().Where(x => x.Code == productNo).Select(x => x.SubstanceId).Distinct().ToList();
            var inquirys = inquiryRepository.GetAll().Where(x => subIds.Contains(x.SubId))
                .Select(x => new GetInquiryOutPut()
            {
                InquiryId = x.Id,
                AdminId = x.AdminId,
                CreateOn = x.CreateOn,
                CustomerName = x.CustomerName,
                CustomerNo = x.CustomerNo,
                Files = x.Files,
                TaFiles = x.SynthFiles,

                Status = x.Status,
                StatusStr = x.Status.ToString(),
                Indication = x.Indication,
                InquiryNo = x.InquiryNo,
                IsDeveSpecial = x.IsDeveSpecial,
                IsDeveSynth = x.IsDeveSynth,
                IsSafe = x.IsSafe,
                NeedCurNum = x.NeedCurNum,
                NeedMaxNum = x.NeedMaxNum,
                Phase = x.Phase,
                ProductName = x.ProductName,
                ProjectName = x.ProjectName,
                ProjectNo = x.ProjectNo,
                ProjectType = x.ProjectType,
                Purpose = x.Purpose,
                SubId = x.SubId,
                TargetDate = x.TargetDate,
                WeekReport = x.WeekReport
            }).ToList();
            bool permissionToViewCustomer = permissionService.HasSysPermission((long)userId, ProjectFunctions.客户查看);

            foreach (var item in inquirys)
            {
                var u = userManager.GetUserById(item.AdminId);
                item.AdminName = u.UserName;
                if (!permissionToViewCustomer)
                {
                    item.CustomerName = "******";
                }
            }
            return new PagedResultOutput<GetInquiryOutPut>(inquirys.Count, inquirys);
        }


        [UnitOfWork(isTransactional: false)]
        public PagedResultOutput<GetInquiryOutPut> GetAll(GetInquiryInPut input)
        {
            var userId = AbpSession.UserId;
            bool subSearch = false;
            List<int> subIds = new List<int>();
            List<string> qCasLst = new List<string>();
            List<string> qsubnameLst = new List<string>();

            if (!string.IsNullOrEmpty(input.CAS))
            {
                subSearch = true;
                qCasLst.Add(input.CAS);
            }

            if (!string.IsNullOrEmpty(input.SubName))
            {
                qsubnameLst.Add(input.SubName);
                subSearch = true;
            }

            if (subSearch)
            {
                subIds = substanceManager.Query(qCasLst, qsubnameLst, new List<string>(), new List<string>()).Select(x => x.Id).ToList();
            }

            var query = inquiryRepository.GetAll();
            if (!string.IsNullOrEmpty(input.CustomerName))
            {
                query = query.Where(x => x.CustomerName.Contains(input.CustomerName));
            }
            if (!string.IsNullOrEmpty(input.Dte))
            {
                System.DateTime dte = System.DateTime.Now;
                DateTime.TryParse(input.Dte, out dte);
                query = query.Where(x => x.CreateOn < dte);
            }
            if (!string.IsNullOrEmpty(input.Dts))
            {
                System.DateTime dts = System.DateTime.Now;
                DateTime.TryParse(input.Dts, out dts);
                query = query.Where(x => x.CreateOn >= dts);
            }
            if (!string.IsNullOrEmpty(input.ProductNo))
            {
                query = query.Where(x => x.ProductName.Contains(input.ProductNo));
            }
            if (!string.IsNullOrEmpty(input.ProjectNo))
            {
                query = query.Where(x => x.ProjectName.Contains(input.ProjectNo));

            }
            if (!string.IsNullOrEmpty(input.QuiryNo))
            {
                query = query.Where(x => x.InquiryNo.Contains(input.QuiryNo));
            }

            if (subSearch)
            {
                query = query.Where(x => subIds.Contains(x.SubId));
            }

            if (!string.IsNullOrWhiteSpace(input.PMName))
            {
                var userIds = userManager.Users.Where(x => x.Name.Contains(input.PMName) || x.UserName.Contains(input.PMName)).Select(x => x.Id);
                query = query.Where(x => userIds.Contains(x.AdminId));
            }

            if (input.status != null && (int)input.status > 0)
            {
                Inquiry.InquiryStatus _status = (Inquiry.InquiryStatus)input.status;
                query = query.Where(x => x.Status == _status);
            }

            if (input.proStatus == -1)
            {
                query = query.Where(x => x.InquiryNo == "");
            }
            else if (input.proStatus == 1)
            {
                query = query.Where(x => x.InquiryNo != "");
            }

            var curQuanCodes = UserQuanRepository.GetAll().Where(x => userId == x.UserId).Select(x => x.QuanCode).ToList();
            List<long> subUserIds = UserQuanRepository.GetAll().Where(x => curQuanCodes.Any(y => x.QuanCode.StartsWith(y))).Select(x => x.UserId).Distinct().ToList();
            subUserIds.Add((long)userId);
            query = query.Where(x => subUserIds.Contains((long)x.CreatorUserId));

            bool permissionToViewCustomer = permissionService.HasSysPermission((long)userId, ProjectFunctions.客户查看);

            var total = query.Count();
            var results = query
                .OrderBy(input.Sorting)
                .Skip(input.SkipCount)
                .Take(input.MaxResultCount)
                .Select(x => new GetInquiryOutPut()
            {
                InquiryId = x.Id,
                AdminId = x.AdminId,
                CreatorId = (long)x.CreatorUserId,
                CreateBy = "",
                CreateOn = x.CreateOn,
                CustomerName = x.CustomerName,
                CustomerNo = x.CustomerNo,
                Files = x.Files,
                TaFiles = x.SynthFiles,
                Status = x.Status,
                StatusStr = x.Status.ToString(),
                Indication = x.Indication,
                InquiryNo = x.InquiryNo,
                IsDeveSpecial = x.IsDeveSpecial,
                IsDeveSynth = x.IsDeveSynth,
                IsSafe = x.IsSafe,
                NeedCurNum = x.NeedCurNum,
                NeedMaxNum = x.NeedMaxNum,
                Phase = x.Phase,
                ProductName = x.ProductName,
                ProjectName = x.ProjectName,
                ProjectNo = x.ProjectNo,
                ProjectType = x.ProjectType,
                Purpose = x.Purpose,
                SubId = x.SubId,
                TargetDate = x.TargetDate,
                WeekReport = x.WeekReport
            }).ToList();

            Dictionary<int, Abp.Mtrl.Material> dicSub = new Dictionary<int, Abp.Mtrl.Material>();
            foreach (var item in results)
            {
                if (item.SubId > 0)
                {
                    if (!dicSub.ContainsKey(item.SubId))
                    {
                        dicSub.Add(item.SubId, substanceManager.Get(item.SubId));
                    }

                    item.SubCas = dicSub[item.SubId].CASNo;
                    item.SubName = dicSub[item.SubId].CnName;
                }
                var u = userManager.GetUserById(item.AdminId);
                item.AdminName = u.UserName;
                var u2 = userManager.GetUserById(item.CreatorId);
                item.CreateBy = u2.UserName;

                if (!permissionToViewCustomer)
                {
                    item.CustomerName = "******";
                }
            }


            return new PagedResultOutput<GetInquiryOutPut>(total, results);
        }


        [UnitOfWork(isTransactional: false)]
        public PagedResultOutput<GetInquiryOutPut> GetTAAll(GetInquiryInPut input)
        {
            var userId = AbpSession.UserId;
            bool subSearch = false;
            List<int> subIds = new List<int>();
            List<string> qCasLst = new List<string>();
            List<string> qsubnameLst = new List<string>();

            if (!string.IsNullOrEmpty(input.CAS))
            {
                subSearch = true;
                qCasLst.Add(input.CAS);
            }

            if (!string.IsNullOrEmpty(input.SubName))
            {
                qsubnameLst.Add(input.SubName);
                subSearch = true;
            }

            if (subSearch)
            {
                subIds = substanceManager.Query(qCasLst, qsubnameLst, new List<string>(), new List<string>()).Select(x => x.Id).ToList();
            }

            var query = inquiryRepository.GetAll();
            if (!string.IsNullOrEmpty(input.CustomerName))
            {
                query = query.Where(x => x.CustomerName.Contains(input.CustomerName));
            }
            if (!string.IsNullOrEmpty(input.Dte))
            {
                System.DateTime dte = System.DateTime.Now;
                DateTime.TryParse(input.Dte, out dte);
                query = query.Where(x => x.CreateOn < dte);
            }
            if (!string.IsNullOrEmpty(input.Dts))
            {
                System.DateTime dts = System.DateTime.Now;
                DateTime.TryParse(input.Dts, out dts);
                query = query.Where(x => x.CreateOn >= dts);
            }
            if (!string.IsNullOrEmpty(input.ProductNo))
            {
                query = query.Where(x => x.ProductName.Contains(input.ProductNo));
            }
            if (!string.IsNullOrEmpty(input.ProjectNo))
            {
                query = query.Where(x => x.ProjectName.Contains(input.ProjectNo));

            }
            if (!string.IsNullOrEmpty(input.QuiryNo))
            {
                query = query.Where(x => x.InquiryNo.Contains(input.QuiryNo));
            }

            if (subSearch)
            {
                query = query.Where(x => subIds.Contains(x.SubId));
            }

            if (!string.IsNullOrWhiteSpace(input.PMName))
            {
                var userIds = userManager.Users.Where(x => x.Name.Contains(input.PMName) || x.UserName.Contains(input.PMName)).Select(x => x.Id);
                query = query.Where(x => userIds.Contains(x.AdminId));
            }

            if (input.status != null && (int)input.status > 0)
            {
                Inquiry.InquiryStatus _status = (Inquiry.InquiryStatus)input.status;
                query = query.Where(x => x.Status == _status);
            }

            var curQuanCodes = UserQuanRepository.GetAll().Where(x => userId == x.UserId).Select(x => x.QuanCode).ToList();
            List<long> subUserIds = UserQuanRepository.GetAll().Where(x => curQuanCodes.Any(y => x.QuanCode.StartsWith(y))).Select(x => x.UserId).Distinct().ToList();
            subUserIds.Add((long)userId);
            query = query.Where(x => subUserIds.Contains(x.AdminId));




            var total = query.Count();
            var results = query
                .OrderBy(input.Sorting)
                .Skip(input.SkipCount)
                .Take(input.MaxResultCount)
                .Select(x => new GetInquiryOutPut()
                {
                    InquiryId = x.Id,
                    AdminId = x.AdminId,
                    CreateBy = "",
                    CreatorId = (long)x.CreatorUserId,
                    CreateOn = x.CreateOn,
                    CustomerName = x.CustomerName,
                    CustomerNo = x.CustomerNo,
                    Files = x.Files,
                    TaFiles = x.SynthFiles,
                    Status = x.Status,
                    StatusStr = x.Status.ToString(),
                    Indication = x.Indication,
                    InquiryNo = x.InquiryNo,
                    IsDeveSpecial = x.IsDeveSpecial,
                    IsDeveSynth = x.IsDeveSynth,
                    IsSafe = x.IsSafe,
                    NeedCurNum = x.NeedCurNum,
                    NeedMaxNum = x.NeedMaxNum,
                    Phase = x.Phase,
                    ProductName = x.ProductName,
                    ProjectName = x.ProjectName,
                    ProjectNo = x.ProjectNo,
                    ProjectType = x.ProjectType,
                    Purpose = x.Purpose,
                    SubId = x.SubId,
                    TargetDate = x.TargetDate,
                    WeekReport = x.WeekReport
                }).ToList();
            bool permissionToViewCustomer = permissionService.HasSysPermission((long)userId, ProjectFunctions.客户查看);

            Dictionary<int, Abp.Mtrl.Material> dicSub = new Dictionary<int, Abp.Mtrl.Material>();
            foreach (var item in results)
            {
                if (item.SubId > 0)
                {
                    if (!dicSub.ContainsKey(item.SubId))
                    {
                        dicSub.Add(item.SubId, substanceManager.Get(item.SubId));
                    }

                    item.SubCas = dicSub[item.SubId].CASNo;
                    item.SubName = dicSub[item.SubId].CnName;
                }
                var u = userManager.GetUserById(item.AdminId);
                item.AdminName = u.UserName;
                var u2 = userManager.GetUserById(item.CreatorId);
                item.CreateBy = u2.UserName;

                if (!permissionToViewCustomer)
                {
                    item.CustomerName = "******";
                }
            }


            return new PagedResultOutput<GetInquiryOutPut>(total, results);
        }


        [UnitOfWork(isTransactional: false)]
        public GetInquiryOutPut Get(int id)
        {
            return GetInquiry(id);
        }

        private GetInquiryOutPut GetInquiry(int id)
        {
            var userId = AbpSession.UserId;
            var x = inquiryRepository.Get(id);
            var inquiry = new GetInquiryOutPut()
            {
                InquiryId = x.Id,
                AdminId = x.AdminId,
                CreateOn = x.CreateOn,
                CustomerName = x.CustomerName,
                CreatorId = (long)x.CreatorUserId,
                CustomerNo = x.CustomerNo,
                Files = x.Files,
                TaFiles = x.SynthFiles,
                Status = x.Status,
                Indication = x.Indication,
                InquiryNo = x.InquiryNo,
                IsDeveSpecial = x.IsDeveSpecial,
                IsDeveSynth = x.IsDeveSynth,
                IsSafe = x.IsSafe,
                NeedCurNum = x.NeedCurNum,
                NeedMaxNum = x.NeedMaxNum,
                Phase = x.Phase,
                ProductName = x.ProductName,
                ProjectName = x.ProjectName,
                ProjectNo = x.ProjectNo,
                ProjectType = x.ProjectType,
                Purpose = x.Purpose,
                SubId = x.SubId,
                TargetDate = x.TargetDate,
                WeekReport = x.WeekReport
            };
            var sub = substanceManager.Get(inquiry.SubId);
            bool permissionToViewCustomer = permissionService.HasSysPermission((long)userId, ProjectFunctions.客户查看);


            inquiry.SubCas = sub.CASNo;
            inquiry.SubName = sub.CnName;



            inquiry.MF = sub.MolecularFormula;
            inquiry.MW = sub.MolecularWeight;
            inquiry.IMG = sub.ImgFile != null ? Convert.ToBase64String(sub.ImgFile) : string.Empty;
            inquiry.ImgBt = sub.ImgFile;

            var u = userManager.GetUserById(inquiry.AdminId);
            inquiry.AdminName = u.UserName;
            var u2 = userManager.GetUserById(inquiry.CreatorId);
            inquiry.CreateBy = u2.UserName;

            if (!permissionToViewCustomer)
            {
                inquiry.CustomerName = "******";
            }
            return inquiry;
        }

        [UnitOfWork(isTransactional: false)]
        public void Create(CreateInquiryInPut input)
        {
            var userId = AbpSession.UserId;
            bool permissionToViewCustomer = permissionService.HasSysPermission((long)userId, ProjectFunctions.客户查看);

            //if (inquiryRepository.GetAll().Any(x => x.InquiryNo == input.InquiryNo && x.SubId != input.SubId))
            //{
            //    throw new Abp.UI.UserFriendlyException("系统提示", "询盘号已占用");
            //}

            var inquiry = new Inquiry.Inquiry() { };

            if (input.Id > 0)
            {
                inquiry = inquiryRepository.Get(input.Id);
            }

            inquiry.AdminId = input.AdminId;
            inquiry.CreateOn = input.CreateOn;
            if (permissionToViewCustomer)
            {
                inquiry.CustomerName = input.CustomerName;
            }


            inquiry.CustomerNo = input.CustomerNo;
            inquiry.Files = input.Files;
            inquiry.Indication = input.Indication;
            //inquiry.InquiryNo = input.InquiryNo;
            inquiry.IsDeveSpecial = input.IsDeveSpecial;
            inquiry.IsDeveSynth = input.IsDeveSynth;
            inquiry.IsSafe = input.IsSafe;
            inquiry.NeedCurNum = input.NeedCurNum;
            inquiry.NeedMaxNum = input.NeedMaxNum;
            inquiry.Phase = input.Phase;
            inquiry.ProductName = input.ProductName;
            inquiry.ProjectName = input.ProjectName;
            inquiry.ProjectNo = input.ProjectNo;
            inquiry.ProjectType = input.ProjectType;
            inquiry.Purpose = input.Purpose;
            inquiry.SubId = input.SubId;
            inquiry.TargetDate = input.TargetDate;
            inquiry.WeekReport = Inquiry.WeekReportEnum.每周报;

            if (input.Id > 0)
            {
                inquiryRepository.Update(inquiry);
            }
            else
            {
                inquiry.Status = Inquiry.InquiryStatus.待工艺评估;
                inquiryRepository.Insert(inquiry);


                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["询盘数量"] = "1";
                StringBuilder sb = new StringBuilder(); sb.Append(@"<style type='text/css'> 
table 
{ 
border-collapse: collapse; 
border: none; 
width: 200px; 
} 
td 
{ 
border: solid #000 1px; 
} 
</style> ");
                sb.Append("<table border=1>");
                sb.Append("<tr><td>时间</td><td>物质名称</td><td>CAS</td></tr>");

                var sub = substanceManager.Get(inquiry.SubId);
                sb.Append(string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>"
                    , inquiry.CreateOn.ToString("yyyy-MM-dd")
                    , sub.CnName, sub.CASNo));

                sb.Append("</table>");
                dic["询盘明细"] = sb.ToString();
                mailManagerRepository.CreateInquiryTAMailRecord("【新询盘提醒】", dic, MailCatelog.询盘评估提醒, inquiry.AdminId);
            }

        }

        public void CommitTA(CreateInquiryInPut input)
        {
            var inquiry = inquiryRepository.Get(input.Id);
            inquiry.AdminId = input.AdminId;
            inquiry.SubId = input.SubId;
            inquiry.SynthFiles = input.Files;
            inquiry.Status = Inquiry.InquiryStatus.工艺已评估;
            inquiryRepository.Update(inquiry);


            var u = userManager.Users.Where(x => x.Id == inquiry.AdminId).FirstOrDefault();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["九洲代号"] = inquiry.InquiryNo;
            dic["项目流水号"] = inquiry.ProjectNo;
            dic["负责人"] = u.Name;
            mailManagerRepository.CreateInquiryTAMailRecord("", dic, MailCatelog.询盘评估完成提醒, (int)inquiry.CreatorUserId);


        }

        [UnitOfWork(isTransactional: false)]
        public void CommitStatu(CreateInquiryInPut input)
        {
            var inquiry = inquiryRepository.Get(input.Id);
            inquiry.Status = (Inquiry.InquiryStatus)input.status;
            inquiryRepository.Update(inquiry);

            if (inquiry.Status == Inquiry.InquiryStatus.待工艺评估)
            {

                if (!string.IsNullOrWhiteSpace(input.Remark))
                {
                    inquiryReplyRepository.Insert(new Inquiry.InquiryReply()
                    {
                        Content = input.Remark,
                        InquiryId = input.Id
                    });
                }

                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["询盘数量"] = "1";
                dic["备注"] = input.Remark;
                StringBuilder sb = new StringBuilder(); sb.Append(@"<style type='text/css'> 
                                                                    table 
                                                                    { 
                                                                    border-collapse: collapse; 
                                                                    border: none; 
                                                                    width: 200px; 
                                                                    } 
                                                                    td 
                                                                    { 
                                                                    border: solid #000 1px; 
                                                                    } 
                                                                    </style> ");
                sb.Append("<table border=1>");
                sb.Append("<tr><td>时间</td><td>物质名称</td><td>CAS</td></tr>");

                var sub = substanceManager.Get(inquiry.SubId);
                sb.Append(string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>"
                    , inquiry.CreateOn.ToString("yyyy-MM-dd")
                    , sub.CnName, sub.CASNo));

                sb.Append("</table>");
                dic["询盘明细"] = sb.ToString();
                mailManagerRepository.CreateInquiryTAMailRecord("【重新询盘提醒】", dic, MailCatelog.询盘评估提醒, inquiry.AdminId);
            }
            else if (inquiry.Status == Inquiry.InquiryStatus.下达生成任务)
            {
                var u = userManager.Users.Where(x => x.Id == inquiry.CreatorUserId).FirstOrDefault();
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["九洲代号"] = inquiry.InquiryNo;
                dic["项目流水号"] = inquiry.ProjectNo;
                dic["销售人员"] = u.Name;
                mailManagerRepository.CreateInquiryTAMailRecord("", dic, MailCatelog.询盘任务下达提醒, inquiry.AdminId);
            }
        }


        [UnitOfWork(isTransactional: false)]
        public void GetInquiryExport(int id)
        {
            string filePath = @"App_Data\report_tpl\询盘书.doc";
            var year = DateTime.Now.Year;
            var week = DateHelper.GetWeek(DateTime.Now);

            var inquiry = GetInquiry(id);

            WordHelper helper = new WordHelper();
            var stream = helper.InquiryXml(inquiry, filePath);

            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ClearHeaders();
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Charset = "utf-8";
            System.Web.HttpContext.Current.Response.ContentType = "application/msword";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition",
                "Attachment;FileName=" + HttpUtility.UrlEncode(inquiry.InquiryNo + "_inquiry.doc", Encoding.UTF8));
            System.Web.HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;


            string outputPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"Logs\inquiryXML.doc";
            FileInfo file = new FileInfo(outputPath);
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", file.Length.ToString());

            System.Web.HttpContext.Current.Response.WriteFile(file.FullName);


            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }


        [UnitOfWork(isTransactional: false)]
        public void GetProjectExport(int id)
        {
            string filePath = @"App_Data\report_tpl\生产任务书.doc";


            var inquiry = GetInquiry(id);

            WordHelper helper = new WordHelper();
            var stream = helper.InquiryXml(inquiry, filePath);

            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ClearHeaders();
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Charset = "utf-8";
            System.Web.HttpContext.Current.Response.ContentType = "application/msword";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition",
                "Attachment;FileName=" + HttpUtility.UrlEncode(inquiry.ProjectNo + "_project.doc", Encoding.UTF8));
            System.Web.HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;


            string outputPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"Logs\inquiryXML.doc";
            FileInfo file = new FileInfo(outputPath);
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", file.Length.ToString());

            System.Web.HttpContext.Current.Response.WriteFile(file.FullName);


            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }

        [UnitOfWork(isTransactional: false)]
        public void GenerateMails()
        {
            var lst = inquiryRepository.GetAll().Where(x => x.Status == Inquiry.InquiryStatus.待工艺评估).ToList();
            var userIds = lst.Select(x => x.AdminId).Distinct().ToList();
            foreach (var userId in userIds)
            {
                /*添加日志*/
                Dictionary<string, string> dic = new Dictionary<string, string>();
                var itemLst = lst.Where(x => x.AdminId == userId).ToList();

                dic["询盘数量"] = itemLst.Count.ToString();

                StringBuilder sb = new StringBuilder();
                sb.Append(@"<style type='text/css'> 
table 
{ 
border-collapse: collapse; 
border: none; 
width: 200px; 
} 
td 
{ 
border: solid #000 1px; 
} 
</style> ");
                sb.Append("<table border=1>");
                sb.Append("<tr><td>时间</td><td>物质名称</td><td>CAS</td></tr>");
                foreach (var item in itemLst)
                {
                    var sub = substanceManager.Get(item.SubId);
                    sb.Append(string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>"
                        , item.CreateOn.ToString("yyyy-MM-dd")
                        , sub.CnName, sub.CASNo));
                }
                sb.Append("</table>");
                dic["询盘明细"] = sb.ToString();
                mailManagerRepository.CreateInquiryTAMailRecord("【每日提醒】", dic, MailCatelog.询盘评估提醒, userId);
            }
        }
    }
}
